package com.gjx.clock.ui

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceFragmentCompat
import com.gjx.clock.AlarmHelper
import com.gjx.clock.AppDatabase
import com.gjx.clock.ClockApplication
import com.gjx.clock.R
import com.gjx.clock.entity.NormalAlarmClock
import kotlinx.android.synthetic.main.normal_clock_item.*
import kotlinx.android.synthetic.main.normal_settings_activity.*
import java.util.*
import kotlin.concurrent.thread

class NormalClockSettingsActivity : AppCompatActivity() {

    lateinit var clock:NormalAlarmClock
    private val normalClockDao = AppDatabase.getDatabase(ClockApplication.context).normalClockDao()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.normal_settings_activity)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val isAddAlarm = intent.extras!!.containsKey("addAlarm")
        if(isAddAlarm){
            val calendar = Calendar.getInstance()
            clock = NormalAlarmClock(
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
            )
            //没有删除选项
            deleteNormalBtn.visibility = View.GONE
        }else{
            var clockId = intent.extras!!["clockId"] as Long
            clock = normalClockDao.getClockById(clockId)
            clock.enable=true
        }

        timePicker.hour=clock.hour
        timePicker.minute=clock.minute

        setEveryday.isChecked = clock.everday

        // 保存闹钟
        saveNormalBtn.setOnClickListener {
            clock.hour = timePicker.hour.toInt()
            clock.minute = timePicker.minute.toInt()
            clock.everday = setEveryday.isChecked
            if(clock.enable){
                AlarmHelper.cancelAlarm(this,clock,false)
                AlarmHelper.setAlarm(this,clock,true)
            }
            thread {
                if (isAddAlarm){
                    normalClockDao.insertClock(clock)
                }else{
                    normalClockDao.updateClock(clock)
                }
            }
            finish()
        }
        // 取消设置
        cancelNormalBtn.setOnClickListener {
            finish()
        }
        //删除闹钟
        deleteNormalBtn.setOnClickListener {
            AlarmHelper.cancelAlarm(this,clock)
            thread {
                normalClockDao.deleteClock(clock)
            }
            finish()
        }

    }


}